<script setup>
import {
  onMounted,
  ref,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
} from "vue";
import loadJs from "@/utils/loadJs";
import { robotInspectionLog } from "@/api/inspection/environment-monitor";
import { useRoute } from "vue-router";
import { getByCode as fetchCamera } from "@/api/robot-camera";
import Cookie from "js-cookie";
import { ElNotification } from "element-plus";

const videoDom = ref(null);

/**
 * @description: 抓图
 * @return {*}
 */
function clickCapturePic() {
  let szPicName = `${new Date().getTime()}.jpg`;

  window.I2_CapturePic(szPicName, {
    bDateDir: true,
  });
}

// 录像loading
const recordLoading = ref(false);
/**
 * @description: 开始录像
 * @return {*}
 */
function clickStartRecord() {
  const szFileName = new Date().getTime();

  window.I_StartRecord(szFileName, {
    bDateDir: true,
    success() {
      updateRecordLoading(true);
    },
    error() {
      ElNotification({
        message: "录像启动失败",
        type: "error",
      });
    },
  });
}

/**
 * @description: 结束录像
 * @return {*}
 */
function clickStopRecord() {
  window.I_StopRecord({
    success() {
      updateRecordLoading(false);
    },
    error() {
      ElNotification({
        message: "录像失败",
        type: "error",
      });
      updateRecordLoading(false);
    },
  });
}

/**
 * @description: 控制运动
 * @param {*} index
 * @return {*}
 */
function mouseDownPTZControl(index) {
  window.I_PTZControl(index, false, {
    iPTZSpeed: 4,
  });
}

function mouseUpPTZControl() {
  window.I_PTZControl(1, true);
}

// 控制映射
const controlButton = [
  { name: "左上", key: 5 },
  { name: "上", key: 1 },
  { name: "右上", key: 7 },
  { name: "左", key: 3 },
  { name: "自动", key: 9 },
  { name: "右", key: 4 },
  { name: "左下", key: 6 },
  { name: "下", key: 2 },
  { name: "右下", key: 8 },
];

let timer;
const route = useRoute();
const robotData = ref({});
async function init() {
  clearTimeout(timer);
  const { data } = await robotInspectionLog(route.query.id);
  if (data) {
    robotData.value = data;
  }
  timer = setTimeout(() => init(), 5000);
}

// 加载视频loading
const loading = ref(false);

onMounted(async () => {
  updateLoading(true);
  await getCamera();
  setVideoHeight();
  initCamera();
});

const wheelStatus = ref(true);

// 摄像头信息
const oLiveView = ref({});

/**
 * @description: 获取绑定的摄像头数据
 * @return {*}
 */
async function getCamera() {
  const { id, rType } = route.query;
  const { data } = await fetchCamera(id, rType);
  if (data.length > 0) {
    oLiveView.value = data[0];
    Cookie.set("hikvision_proxy_ip", oLiveView.value.ip);
    Cookie.set("hikvision_proxy_port", oLiveView.value.port);
    Cookie.set("hikvision_proxy_ws_port", oLiveView.value.uuid);
  }
  return true;
}

/**
 * @description: 初始化摄像头
 * @return {*}
 */
async function initCamera() {
  await loadPlugin();
  await window.I_InitPlugin(
    videoDom.value.clientWidth,
    videoDom.value.clientHeight,
    {
      bWndFull: true,
      iWndowType: 1,
      cbInitPluginComplete: onInitPlugin,
    }
  );
}

/**
 * @description: 加载插件
 * @return {*}
 */
async function loadPlugin() {
  await loadJs("/hikvision/jquery-1.12.1.min.js");
  await loadJs("/hikvision/cryptico.min.js");
  await loadJs("/hikvision/webVideoCtrl.js");
  return true;
}

/**
 * @description: 初始化插件后的回调
 * @return {*}
 */
function onInitPlugin() {
  window.I_InsertOBJECTPlugin("player");
  login();
}

/**
 * @description: 计算 video 高度
 * @return {*}
 */
function setVideoHeight() {
  const height = videoDom.value.clientHeight;
  videoDom.value.style.height = `${height}px`;
}

/**
 * @description: 登录设备
 * @return {*}
 */
function login() {
  window.I_Login(
    oLiveView.value.ip,
    1,
    oLiveView.value.port,
    oLiveView.value.user,
    oLiveView.value.password,
    {
      success: onLoginSuccess,
      error: onLoginError,
    }
  );
}

/**
 * @description: 登录成功后的回调
 * @return {*}
 */
function onLoginSuccess() {
  const szDeviceIdentify = `${oLiveView.value.ip}_${oLiveView.value.port}`;
  setTimeout(() => {
    window.I_StartRealPlay(szDeviceIdentify, {
      success: onPlaySuccess,
      error: onPlayError,
      iStreamType: 2,
      iPort: oLiveView.value.rtsp,
    });
  }, 1000);
}

/**
 * @description: 登录失败回调
 * @return {*}
 */
function onLoginError() {
  ElNotification({
    message: "登录摄像头失败",
    type: "error",
  });
}

/**
 * @description: 预览成功回调
 * @return {*}
 */
function onPlaySuccess() {
  updateLoading(false);
}

/**
 * @description: 预览失败回调
 * @return {*}
 */
function onPlayError() {
  ElNotification({
    message: "预览失败",
    type: "error",
  });
}

/**
 * @description: 更新加载视频loading
 * @param {*} value
 * @return {*}
 */
function updateLoading(value) {
  loading.value = value;
}

/**
 * @description: 更新录像loading
 * @param {*} value
 * @return {*}
 */
function updateRecordLoading(value) {
  recordLoading.value = value;
}

onBeforeUnmount(() => {
  window.I_Stop();
  const szDeviceIdentify = `${oLiveView.value.ip}_${oLiveView.value.port}`;
  window.I_Logout(szDeviceIdentify);
});

onActivated(() => {
  init();
});

onDeactivated(() => {
  clearTimeout(timer);
});
</script>

<template>
  <el-container class="h-full">
    <el-main class="mb-4 p-0">
      <div class="flex h-full">
        <div
          v-loading="loading"
          class="bg-[#162331] rounded flex-1 mr-4 relative"
        >
          <div id="player" ref="videoDom" class="h-full"></div>
          <el-popover trigger="click" width="314px">
            <template #reference>
              <el-button class="absolute top-4 right-4" type="primary"
                >云台控制</el-button
              >
            </template>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-button @click="clickCapturePic">抓图</el-button>
              </el-col>
              <el-col :span="8">
                <el-button :loading="recordLoading" @click="clickStartRecord">
                  开始录像
                </el-button>
              </el-col>
              <el-col :span="8">
                <el-button @click="clickStopRecord">停止录像</el-button>
              </el-col>
              <el-col v-for="item in controlButton" :key="item.key" :span="8">
                <el-button
                  @mousedown="mouseDownPTZControl(item.key)"
                  @mouseup="mouseUpPTZControl"
                >
                  {{ item.name }}
                </el-button>
              </el-col>
            </el-row>
          </el-popover>
        </div>
        <div class="bg-[#162331] rounded flex-1"></div>
      </div>
    </el-main>
    <el-footer height="150px" class="p-0">
      <div class="h-full bg-[#162331] rounded flex items-center px-4">
        <div class="flex-1">
          <div class="text-[#85939D] mb-4">电量</div>
          <div class="w-96">
            <el-progress :percentage="robotData.battery" />
          </div>
        </div>
        <div class="flex-1">
          <div class="text-[#85939D] mb-4">机器人编号</div>
          <div class="text-lg font-bold">{{ robotData.robotid }}</div>
        </div>
        <div class="flex-1">
          <div class="text-[#85939D] mb-4">任务状态</div>
          <div class="text-lg font-bold">
            {{ wheelStatus ? "任务中" : "无" }}
          </div>
        </div>
      </div>
    </el-footer>
  </el-container>
</template>

<style scoped>
.el-button + .el-button {
  margin-left: 4px;
}

.el-button {
  width: 88px;
  margin: 4px;
}

:deep(.draw-window),
:deep(.parent-wnd) {
  border: 0 !important;
  border-radius: 0.25rem;
}

:deep(.el-progress-bar__outer) {
  height: 16px !important;
  background-color: #5e6867;
}

:deep(.el-progress__text) {
  font-size: 18px !important;
  color: white;
}
</style>
